package com.bigtotoro.shuiyincamera.video;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoItem;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.filter.FilterAdjuster;
import com.bigtotoro.shuiyincamera.video.filter.FilterType;
import com.bigtotoro.shuiyincamera.video.filter.MovieWrapperView;
import com.bigtotoro.shuiyincamera.video.filter.PlayerTimer;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.daasuu.gpuv.composer.FillMode;
import com.daasuu.gpuv.composer.GPUMp4Composer;
import com.daasuu.gpuv.egl.filter.GlFilter;
import com.daasuu.gpuv.egl.filter.GlFilterGroup;
import com.daasuu.gpuv.egl.filter.GlMonochromeFilter;
import com.daasuu.gpuv.egl.filter.GlVignetteFilter;
import com.daasuu.gpuv.player.GPUPlayerView;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import qiu.niorgai.StatusBarCompat;
import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

/**
 * 视频滤镜
 */
public class VideoFilterActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "video-filter";

    private GPUPlayerView gpuPlayerView;
    private SimpleExoPlayer player;
    private ImageView btnPlay;
    private SeekBar timeSeekBar;
    private SeekBar filterSeekBar;
    private PlayerTimer playerTimer;
    private GlFilter filter;
    private FilterAdjuster adjuster;

    private FrameLayout frameLayout;
    private String videoPath;
    private VideoItem videoItem;
    private int selectPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_filter);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black));
        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoFilterActivity.this, "video_lvjing", "视频滤镜");

        videoPath = getIntent().getStringExtra("path");
        videoItem = VideoUtil.createVideoItem(videoPath);
        setUpViews();
        initRecycleview();

        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);
        frameLayout = findViewById(R.id.v_root);
        frameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                calVideoSize();
            }
        }, 200);
    }

    private void calVideoSize(){
        int videoWidth = videoItem.getWidth();
        int videoHeight = videoItem.getHeight();

        FrameLayout videoLayout = findViewById(R.id.layout_movie_wrapper);

        int frameWidth = frameLayout.getWidth();
        int frameHeight = frameLayout.getHeight();
        Log.d(TAG, "frame" + frameWidth + ":" + frameHeight); //1080:1500
        Log.d(TAG, "video" + videoWidth + ":" + videoHeight); //1920:1080
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

        float xScale = (float) frameWidth / videoWidth;
        float yScale = (float) frameHeight / videoHeight;

        //For Center Crop use the Math.max to calculate the scale
        //float scale = Math.max(xScale, yScale);
        //For Center Inside use the Math.min scale.
        //I prefer Center Inside so I am using Math.min
        float scale = Math.min(xScale, yScale);

        float scaledWidth = scale * videoWidth;
        float scaledHeight = scale * videoHeight;
//        float scaledWidth =  videoWidth;
//        float scaledHeight =  videoHeight;
        Log.i("视频拼接","videoWidth==="+videoWidth+" ,  videoHeight===" + videoHeight);

        //Set the new size for the VideoView based on the dimensions of the video
        ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
        layoutParams.width = (int) scaledWidth;
        layoutParams.height = (int) scaledHeight;
        videoLayout.setLayoutParams(layoutParams);
        videoLayout.invalidate(); //刷新界面
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpSimpleExoPlayer();
        setUoGlPlayerView();
        setUpTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        releasePlayer();
        if (playerTimer != null) {
            playerTimer.stop();
            playerTimer.removeMessages(0);
        }
    }

    private void setUpViews() {
        // play pause
        btnPlay = findViewById(R.id.btn_play);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player == null) return;
                if (btnPlay.getVisibility()==View.INVISIBLE) {
                    player.setPlayWhenReady(false);
                    btnPlay.setImageResource(R.drawable.ic_video_play);
                    btnPlay.setVisibility(View.VISIBLE);
                } else {
                    player.setPlayWhenReady(true);
                    btnPlay.setVisibility(View.INVISIBLE);
                }
            }
        });

        // seek
        timeSeekBar = (SeekBar) findViewById(R.id.timeSeekBar);
        timeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (player == null) return;

                if (!fromUser) {
                    // We're not interested in programmatically generated changes to
                    // the progress bar's position.
                    return;
                }

                player.seekTo(progress * 1000);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // do nothing
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // do nothing
            }
        });

        filterSeekBar = (SeekBar) findViewById(R.id.filterSeekBar);
        filterSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (adjuster != null) {
                    adjuster.adjust(filter, progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // do nothing
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // do nothing
            }
        });


    }

    private RecyclerView listView;
    private BaseQuickAdapter filterAdapter;
    final List<FilterType> filterTypes = FilterType.createFilterList();
    final List<Integer> selectData = new ArrayList<>();
    private void initRecycleview() {
        selectData.add(0);//默认选中0
        listView = findViewById(R.id.list);
//        FilterAdapter filterAdapter = new FilterAdapter(R.layout.item_filter_text, filterTypes);
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new BaseQuickAdapter<FilterType, BaseViewHolder>(
                R.layout.item_filter_text, filterTypes){
            @Override
            protected void convert(BaseViewHolder helper, FilterType filterType) {
                TextView item_name = helper.getView(R.id.item_name);
                if (selectData!=null && selectData.size()>0){
                    int position = selectData.get(0);
                    if (filterTypes.get(position)==filterType){
                        item_name.setEnabled(true);
                        item_name.setBackgroundColor(getResources().getColor(R.color.font_8));
                        item_name.setTextColor(getResources().getColor(R.color.theme_gold02));
                    }else {
                        item_name.setEnabled(false);
                        item_name.setBackgroundColor(getResources().getColor(R.color.font_4a));
                        item_name.setTextColor(getResources().getColor(R.color.white));
                    }
                }

                helper.setText(R.id.item_name, FilterType.getFilterName(filterType, VideoFilterActivity.this));

            }
        };
        listView.setAdapter(filterAdapter);

        filterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i("视频滤镜","选中位置===="+position);
                if (selectData!=null){
                    selectData.clear();
                    selectData.add(position);
                }
                filterAdapter.notifyDataSetChanged();

                filter = FilterType.createGlFilter(filterTypes.get(position), getApplicationContext());
                adjuster = FilterType.createFilterAdjuster(filterTypes.get(position));
                findViewById(R.id.filterSeekBarLayout).setVisibility(adjuster != null ? View.VISIBLE : View.GONE);
                gpuPlayerView.setGlFilter(filter);
                selectPosition = position;

            }
        });
    }


    private void setUpSimpleExoPlayer() {

        TrackSelector trackSelector = new DefaultTrackSelector();

        // Measures bandwidth during playback. Can be null if not required.
        DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "yourApplicationName"), defaultBandwidthMeter);
//        MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(localPath));
        MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.fromFile(new File(videoPath)));

        // SimpleExoPlayer
        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
        // Prepare the player with the source.
        player.prepare(mediaSource);
        player.setPlayWhenReady(true);

    }


    private void setUoGlPlayerView() {
        gpuPlayerView = new GPUPlayerView(this);
        gpuPlayerView.setSimpleExoPlayer(player);
        gpuPlayerView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ((FrameLayout) findViewById(R.id.layout_movie_wrapper)).addView(gpuPlayerView);
        gpuPlayerView.onResume();
    }


    private void setUpTimer() {
        playerTimer = new PlayerTimer();
        playerTimer.setCallback(new PlayerTimer.Callback() {
            @Override
            public void onTick(long timeMillis) {
                long position = player.getCurrentPosition();
                long duration = player.getDuration();

                if (duration <= 0) return;

                timeSeekBar.setMax((int) duration / 1000);
                timeSeekBar.setProgress((int) position / 1000);
            }
        });
        playerTimer.start();
    }


    private void releasePlayer() {
        gpuPlayerView.onPause();
        ((FrameLayout) findViewById(R.id.layout_movie_wrapper)).removeAllViews();
        gpuPlayerView = null;
        player.stop();
        player.release();
        player = null;
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.back){
            finish();
        }else if(view.getId()==R.id.btn_save){

            //添加友盟事件统计
            MyUtils.addUmengEvent(VideoFilterActivity.this, "video_lvjing_save", "视频滤镜保存");

            startActivity(new Intent(this, VideoProgressActivity.class)
                .putExtra("position", selectPosition)
                .putExtra("path", videoPath));
        }
    }



    public static void exportMp4ToGallery(Context context, String filePath) {
        final ContentValues values = new ContentValues(2);
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        values.put(MediaStore.Video.Media.DATA, filePath);
        context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                values);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + filePath)));
    }

}
